package com.quan.upms.rpc.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import tk.mybatis.mapper.entity.Condition;

import com.quan.common.core.support.BaseService;
import com.quan.upms.rpc.api.UpmsPermissionService;
import com.quan.upms.rpc.dao.mapper.UpmsPermissionMapper;
import com.quan.upms.rpc.dao.mapper.UpmsRolePermissionAssignMapper;
import com.quan.upms.rpc.model.UpmsPermission;
import com.quan.upms.rpc.model.UpmsRolePermissionAssign;

@Service
public class UpmsPermissionServiceImpl extends BaseService<UpmsPermission> implements UpmsPermissionService {
	
	@Autowired
	private UpmsPermissionMapper mapper ;
	
	@Autowired
	private UpmsRolePermissionAssignMapper upmsRolePermissionAssignMapper ;
	
	@Override
	public int deleteById(Object id) {
		return recursiveDelete(Integer.valueOf(id.toString()));
	}
	
	private int recursiveDelete(Integer id) {
		List<UpmsPermission> loadChildrenNode = this.selectChildren(id, null) ;
		if(null != loadChildrenNode) {
			for (UpmsPermission permission : loadChildrenNode) {
				
				//删除该角色下的权限关联关系
				Condition condition = new Condition(UpmsRolePermissionAssign.class) ;
				condition.createCriteria().andEqualTo("permissionId", permission.getId());
				this.upmsRolePermissionAssignMapper.deleteByCondition(condition) ;
				
				recursiveDelete(permission.getId());
			}
		}
		return super.deleteById(id) ;
	}

	@Override
	public List<UpmsPermission> selectRoot(UpmsPermission entity) {
		return this.mapper.selectRoot(entity);
	}

	@Override
	public List<UpmsPermission> selectChildren(Integer pid, Integer[] type) {
		return this.mapper.selectChildren(pid, type);
	}

	@Override
	public List<UpmsPermission> tree(UpmsPermission entity) {
		Integer[] type = null ;
		if(null != entity.getType()) {
			type = new Integer[]{entity.getType()} ;
		}
		List<UpmsPermission> list = new ArrayList<UpmsPermission>() ;
		
		List<UpmsPermission> selectRoot = this.selectRoot(entity) ;
		for (UpmsPermission permission : selectRoot) {
			list.add(recursive(permission, type)) ;
		}
		return list;
	}
	
	private UpmsPermission recursive(UpmsPermission permission, Integer[] type) {
		
		List<UpmsPermission> selectChildren = this.selectChildren(permission.getId(), type) ;
		if(null != selectChildren && !selectChildren.isEmpty()) {
			List<UpmsPermission> children = new ArrayList<UpmsPermission>() ;
			
			for (UpmsPermission childPermission : selectChildren) {
				children.add(recursive(childPermission, type)) ;
			}
			
			permission.setChildren(children);
		}
		return permission ;
	}

}
